
package combat.dudes.server.protocol.implementation;

import java.util.ArrayList;

import combat.dudes.protocol.data.ChatEntry;
import combat.dudes.protocol.interfaces.ChatInt;


/**
 * 
 * @author Laurens Andriessen
 * @version 1.0
 */
public class Chat implements ChatInt {

	// Since we only want ONE Chat: create ONE instance of the Chat-class
	// http://radio-weblogs.com/0122027/stories/2003/10/20/implementingTheSingletonPatternInJava.html
	protected Chat() {}
	private static Chat _instance = null;
	public final static Chat instance() {
		if(_instance == null) {
			_instance = new Chat();
		}
		return _instance;
	}

	// Members
	private int lastMessageID = 0;
	private static ArrayList<ChatEntry> chats = new ArrayList<ChatEntry>();

	// Methods
	@Override
	public synchronized int getLastMessageID() {
		return lastMessageID;
	}
	@Override
	public synchronized void setLastMessageID(int lastMessageID) {
		this.lastMessageID = lastMessageID;
	}

	@Override
	public synchronized ArrayList<ChatEntry> getChats() {
		return (chats == null) ? new ArrayList<ChatEntry>() : chats;
	}
	@Override
	public synchronized void setChats(ArrayList<ChatEntry> chats) {
		Chat.chats = chats;
	}

	// ------------------------------------------

	@Override
	public synchronized void sendChat(ChatEntry chat) {
		chats.add(chat);
	}

	@Override
	public int getNewMessageID() {
		return ++lastMessageID;
	}

	@Override
	public synchronized ArrayList<ChatEntry> getNewChats(int lastKnownMessageID) {
		ArrayList<ChatEntry> newChats = new ArrayList<ChatEntry>();
		for(ChatEntry msg : chats)
			if(msg.getMessageID() > lastKnownMessageID)
				newChats.add(msg);

		return newChats;
	}

}
